import { observable, action, computed, runInAction, toJS } from 'mobx';

import BaseStore from '../BaseStore';

class Store extends BaseStore {
    @observable userInfo;
    @observable categories;
    @observable entities;

    //设置权限的类型，1：类目权限，2：企业权限
    @observable modalType;
    //当前操作权限规则
    @observable currentRule;
    @observable currentRuleValue;
    // 类目树
    @observable categoryTree;
    // 合作企业
    @observable enterprises;

    isSuccess = false;
    // 弹框提示的错误
    globalErrMsg = '';

    userId;
    username;
    realname;

    @computed
    get userInfoData() {
        return toJS(this.userInfo);
    }

    @computed
    get categoriesData() {
        return toJS(this.categories);
    }

    @computed
    get entitiesData() {
        return toJS(this.entities);
    }

    @computed
    get categoryTreeData() {
        return toJS(this.categoryTree);
    }

    @computed
    get enterprisesData() {
        return toJS(this.enterprises);
    }

    @computed
    get currentRuleValueData() {
        return toJS(this.currentRuleValue);
    }

    @computed
    get isRuleConfirmBtnDisabled() {
        return !this.currentRuleValue || this.currentRuleValue.length < 1;
    }

    @action
    initUserInfo(userId, username, realname) {
        this.userId = userId;
        this.username = username;
        this.realname = realname;
        this.userInfo = [
            [{
                key: 'username',
                title: '用户名',
                content: username || null,
                labelWidth: 48
            }, {
                key: 'realname',
                title: '姓名',
                content: realname || null,
                labelWidth: 48
            }, {}],
        ];
    }

    @action
    reset() {
        this.userInfo = null;
        this.categories = null;
        this.entities = null;
        this.modalType = null;
        this.currentRule = null;
        this.currentRuleValue = null;
        this.categoryTree = null;
        this.enterprises = null;
        this.isSuccess = false;
        this.globalErrMsg = null;
        this.userId = null;
        this.username = null;
        this.realname = null;
    }

    @action
    addRule(entityNo, ruleGroupIdx) {
        const entity = this.entities[entityNo];
        if (!entity) {
            return;
        }
        const ruleGroup = entity.rules[ruleGroupIdx];
        const rule = {
            field: '',
            op: '',
            value: null,
        }
        if (ruleGroup) {
            ruleGroup.push(rule);
        } else {
            entity.rules[ruleGroupIdx] = [rule];
        }
    }

    /**
     * 改变规则控制项目
     */
    @action
    setRuleProperty(newProperty, entityNo, ruleGroupIdx, ruleIdx) {
        const entity = this.entities[entityNo];
        if (!entity) {
            return;
        }
        const ruleGroup = entity.rules[ruleGroupIdx];
        if (!ruleGroup) {
            return;
        }
        const rule = ruleGroup[ruleIdx];
        if (!rule) {
            return;
        }
        rule.field = newProperty;
        rule.op = 'in';
        rule.value = null;
    }

    /**
     * 改变规则条件
     */
    @action
    setRuleOp(newOp, entityNo, ruleGroupIdx, ruleIdx) {
        const entity = this.entities[entityNo];
        if (!entity) {
            return;
        }
        const ruleGroup = entity.rules[ruleGroupIdx];
        if (!ruleGroup) {
            return;
        }
        const rule = ruleGroup[ruleIdx];
        if (!rule) {
            return;
        }
        rule.op = newOp;
    }

    @action
    deleteRule(entityNo, ruleGroupIdx, ruleIdx) {
        const entity = this.entities[entityNo];
        if (!entity) {
            return;
        }
        const ruleGroup = entity.rules[ruleGroupIdx];
        if (!ruleGroup) {
            return;
        }
        if (!ruleGroup[ruleIdx]) {
            return;
        }
        ruleGroup.splice(ruleIdx);
    }

    @action
    async openModal(ruleData, entityNo, ruleGroupIdx, ruleIdx) {
        if (!ruleData || !ruleData.field) {
            return;
        }
        this.currentRule = {
            entityNo,
            ruleGroupIdx,
            ruleIdx,
        };
        if (ruleData.field === 'category_id') {
            this.modalType = 1;
            if (!this.categoryTree) {
                await this.fetchCategoryTree();
            }
            runInAction(() => {
                this.currentRuleValue = ruleData.value && getRealCheckedTreeNodeIds(this.categoryTreeData, ruleData.value.map(item => parseInt(item))) || null;
            });
        } else {
            this.modalType = 2;
            !this.enterprises && this.fetchEnterprises();
            this.currentRuleValue = ruleData.value && ruleData.value.map(item => parseInt(item)) || null;
        }
        console.log('this.currentRuleValueData');
        console.log(this.currentRuleValueData);
    }

    @action
    closeModal() {
        this.modalType = null;
        this.currentRule = null;
        this.currentRuleValue = null;
    }

    @action
    updateRuleValue() {
        const { entityNo, ruleGroupIdx, ruleIdx } = this.currentRule;
        const entity = this.entities[entityNo];
        if (!entity) {
            return;
        }
        const ruleGroup = entity.rules[ruleGroupIdx];
        if (!ruleGroup) {
            return;
        }
        const rule = ruleGroup[ruleIdx];
        if (!rule) {
            return;
        }
        if (this.currentRuleValue) {
            if (this.modalType === 1) {
                rule.value = getAllCheckedTreeNodeIds(this.categoryTreeData, this.currentRuleValueData.map(item => parseInt(item)));
            } else {
                rule.value = this.currentRuleValueData.map(item => parseInt(item));
            }
            return;
        }
        rule.value = null;
    }

    @action
    async fetchData() {
        if (!this.userId) {
            return;
        }
        const res = await this.get(`/auth/entities/users/${this.userId}/properties-rules`, {
        }, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                const data = res.data;
                const categories = [];
                const entities = {};
                const desc = {
                    '购货类': '购货类功能模块权限主要支撑采购人员完成计划寻源、订单、对账等业务活动。',
                    '销货类': '销货类功能模块权限主要支撑销售人员完成销售报价、销售对账等业务活动。',
                    '收发货类': '收发货类功能模块权限主要支撑发货签收人员完成发货、签收等业务活动。',
                }
                data.forEach((category, idx) => {
                    category.forEach((entity, index) => {
                        const { type, entity_no, property } = entity; 
                        if (!Array.isArray(property)) {
                            entity.property = [property];
                        }
                        if (index === 0) {
                            categories[idx] = {
                                type: type,
                                description: desc[type],
                                entities: [entity_no]
                            };
                        } else {
                            categories[idx].entities.push(entity_no);
                        }
                        entities[entity_no] = entity;
                    });
                });
                this.categories = categories;
                this.entities = entities;
                this.allRules = res.data;

            } else {
                this.categories = null;
                this.entities = null;
                this.allRules = null;
            }
        });
    }

    @action
    async fetchEntityRules(entityNo) {
        if (!entityNo) {
            return;
        }
        const res = await this.get(`/auth/entities/${entityNo}/users/${this.userId}/properties-rules`, null, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.entities[entityNo] = {
                    entity_no: res.data.entity_no,
                    entity_name: res.data.entity_name,
                    property: res.data.property,
                    rules: res.data.rule,
                };
            }
        });
    }

    @action
    async fetchCategoryTree() {
        if (!this.userId) {
            return;
        }
        const res = await this.get('/materials/categories-tree', null, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.categoryTree = res.data;
            } else {
                this.categoryTree = null;
            }
        });
    }

    @action
    async fetchEnterprises() {
        const res = await this.get('/supply-demand/suppliers/cooperation-purchaser', null, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.enterprises = res.data;
            } else {
                this.enterprises = null;
            }
        });
    }

    @action
    validateRules(entityNo) {
        this.globalErrMsg = '';
        const entity = this.entities[entityNo];
        const rules = toJS(entity.rules);
        for (let i = 0, len = rules.length; i < len; i++) {
            const group = rules[i];
            for (let i1 = 0, len1 = group.length; i1 < len1; i1++) {
                const rule = group[i1];
                if (!rule.field || !rule.op || !rule.value || rule.value.length < 1) {
                    this.globalErrMsg = '有规则项内容为空，请检查调整后重新提交';
                    return;
                }
            }
        }
    }

    @action
    async submit(entityNo) {
        this.globalErrMsg = '';
        this.isSuccess = false;
        const entity = this.entities[entityNo];
        const rules = toJS(entity.rules);
        const res = await this.post(`/auth/entities/${entityNo}/rules`, {
            user_id: this.userId,
            rules
        }, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.isSuccess = true;
            } else {
                this.globalErrMsg = res.message || '设置数据权限失败，请重试';
            }
        });
    }
}

//根据真正勾选的树节点id获取所有选中节点id，包括半选状态
function getAllCheckedTreeNodeIds(data, ids) {
    let newIds = [];
    if (!data || !ids || data.length < 1 || ids.length < 1) {
        return null;
    }
    for (let i = 0, len = data.length; i < len; i++) {
        const item = data[i];
        const idx = ids.indexOf(item.id);
        if (item.children && item.children.length) {
            const childrenIds = getAllCheckedTreeNodeIds(item.children, ids);
            if (childrenIds && childrenIds.length) {
                newIds = newIds.concat(childrenIds);
                newIds.push(item.id);
            }
        }
        if (idx !== -1) {
            newIds.indexOf(item.id) === -1 && newIds.push(item.id);
            ids.splice(idx, 1);
            if (ids.length < 1) {
                return newIds;
            }
        }
    }
    return newIds;
}

// 根据后台返回的选中的树的节点获取真正选中的节点id，即过滤掉半选状态的节点
function getRealCheckedTreeNodeIds(data, ids) {
    let newIds = [];
    if (!data || !ids || data.length < 1 || ids.length < 1) {
        return null;
    }
    for (let i = 0, len = data.length; i < len; i++) {
        const item = data[i];
        const idx = ids.indexOf(item.id);
        if (idx !== -1 ) {
            ids.splice(idx, 1);
            if (item.children && item.children.length) {
                const childrenIds = getRealCheckedTreeNodeIds(item.children, ids);
                if (childrenIds && childrenIds.length) {
                    newIds = newIds.concat(childrenIds);
                }
            } else {
                newIds.push(item.id);
            }
            if (ids.length < 1) {
                return newIds;
            }
        }
    }
    return newIds;
}

export default new Store();
